<?php

namespace app\controller;

use app\BaseController;
use app\validate\CheckBanner;
use app\validate\CheckQuick;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use think\Request;

class Picmodule extends BaseController
{
    /*
     * 外部课程
     */
    public function wailist(){
        return View::fetch();
    }

    public function wailist_load(Request $request){
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        $get = $request->get();
        $where = [];
        $where[] = ['start','<>',3];
        $total = Db::name('pic_wailink')
            ->where($where)
            ->count();
        $order = ['sort' => 'asc', 'id' => 'desc'];
        $rows = Db::name('pic_wailink')
            ->where($where)
            ->order($order)
            ->page($get['page'], $get['limit'])
            ->select();
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    //添加
    public function wailist_add(Request $request)
    {

        if ($request->isPost()){
            if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
                return $this->outputAjax('无操作权限');
            }
            $post = $request->post();
            //remove_xss
            $post = remove_xss($post);
            if (empty($post['title'])){
                return $this->outputAjax('中文标题不能为空！',500);
            }
            if (empty($post['title_en'])){
                return $this->outputAjax('英文标题不能为空！',500);
            }
            if (empty($post['img'])){
                return $this->outputAjax('图片不能为空！',500);
            }
            if (empty($post['url'])){
                return $this->outputAjax('跳转地址不能为空！',500);
            }
            try {
                $data = array(
                    'title'       => $post['title'],
                    'title_en'       => $post['title_en'],
                    'images'         => $post['img'],
                    'link'         => $post['url'],
                    'add_time'    => time(),
                    'update_time' => time(),
                );
                if (!Db::name('pic_wailink')->insert($data)) {
                    return $this->outputAjax('操作失败！');
                }
                return $this->outputAjax('操作成功！',0);
            } catch (\Exception $e) {
                return $this->outputAjax($e->getMessage());
            }
        }else{
            if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
                return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
            }
            return View::fetch();
        }

    }

    //修改
    public function wailist_edit(Request $request)
    {
        if ($request->isPost()){
            if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
                return $this->outputAjax('无操作权限');
            }
            $post = $request->post();
            $post = remove_xss($post);
            if (empty($post['title'])){
                return $this->outputAjax('标题不能为空！',500);
            }
            if (empty($post['title_en'])){
                return $this->outputAjax('英文标题不能为空！',500);
            }
            if (empty($post['images'])){
                return $this->outputAjax('图片不能为空！',500);
            }
            if (empty($post['link'])){
                return $this->outputAjax('跳转地址不能为空！',500);
            }
            try {
                $data = array(
                    'title'       => $post['title'],
                    'title_en'       => $post['title_en'],
                    'images'         => $post['images'],
                    'link'         => $post['link'],
                    'add_time'    => time(),
                    'update_time' => time(),
                );
                if (!Db::name('pic_wailink')->where('id',$post['id'])->update($data)) {
                    return $this->outputAjax('修改失败！');
                }
                return $this->outputAjax('修改成功！',0);
            } catch (\Exception $e) {
                return $this->outputAjax($e->getMessage());
            }
        }

        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');
        $inf = Db::name('pic_wailink')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }

    public function wailist_delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $id = $request->post('id');
        try {
            if (!Db::name('pic_wailink')->where('id', 'in', $id)->update(['start' => 3])) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //修改排序
    public function wailist_sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }
        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }
        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }
        Db::startTrans();
        try {

            $res = Db::name('pic_wailink')->where(array('id'=>$post['id']))->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('pic_wailink')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort', 'asc')
                ->select();

            if (!Db::name('pic_wailink')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('pic_wailink')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }
    //状态
    public function wailist_toggle(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        if (!$id = $request->param('id')) {
            return $this->outputAjax();
        }

        try {

            $inf = Db::name('pic_wailink')->field('start')->find($id);

            if (empty($inf)) {
                return $this->outputAjax();
            }

            if (!in_array($inf['start'], array(1, 2))) {
                return $this->outputAjax();
            }
            $status = $inf['start'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'start' => $status,
            );
            if (Db::name('pic_wailink')->update($update)) {
                return $this->outputAjax('操作成功', 0);
            }
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
        return $this->outputAjax('操作失败');
    }




    /*
     * pc 轮播
     */
    public function banner()
    {
        return View::fetch();
    }

    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        if (isset($get['field']) && isset($get['order'])) {
            if ( !empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
                $order = [$field => $sort];
            } else {
                $order = ['sort' => 'asc', 'id' => 'desc'];
            }
        } else {
            $order = ['sort' => 'asc', 'id' => 'desc'];
        }
        $where = [];
        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['title', 'like', '%'.$get['key'].'%'];
            }
        }
        $where[] = ['status', 'in', '1,2'];
        $total = Db::name('pic_banner')
            ->where($where)
            ->count();

        $rows = Db::name('pic_banner')
            ->where($where)
            ->order($order)
            ->page($get['page'], $get['limit'])
            ->select();
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function banner_add()
    {

        return View::fetch();
    }

    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckBanner::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {
            $data = array(
                'title'       => $post['title'],
                'img'         => $post['img'],
                'url'         => $post['url'],
                'type'         => $post['type'],
                'add_time'    => time(),
                'update_time' => time(),
            );
            if (!Db::name('pic_banner')->insert($data)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
     * 修改
     */
    public function banner_edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');
        $inf = Db::name('pic_banner')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }



    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }
        $post = $request->post();
        $post = remove_xss($post);
        try {
            $update = array(
                'id'          => $post['id'],
                'title'       => $post['title'],
                'img'         => $post['img'],
                'url'         => $post['url'],
                'type'         => $post['type'],
                'update_time' => time(),
            );
            if (!Db::name('pic_banner')->update($update)) {
                return $this->outputAjax('操作失败！');
            }
            return $this->outputAjax('操作成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    //+banner显示or隐藏
    public function toggle(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        if (!$id = $request->param('id')) {
            return $this->outputAjax();
        }

        try {

            $inf = Db::name('pic_banner')->field('status')->find($id);

            if (empty($inf)) {
                return $this->outputAjax();
            }

            if (!in_array($inf['status'], array(1, 2))) {
                return $this->outputAjax();
            }

            $status = $inf['status'] == 1 ? 2 : 1;

            $update = array(
                'id' => $id,
                'status' => $status,
            );
            if (Db::name('pic_banner')->update($update)) {
                return $this->outputAjax('操作成功', 0);
            }
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
        return $this->outputAjax('操作失败');
    }

    //+banner删除
    public function delete(Request $request)
    {
//        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
//            return $this->outputAjax('无操作权限');
//        }

        $id = $request->post('id');

        try {
            if (!Db::name('pic_banner')->where('id', 'in', $id)->update(['status' => 3])) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    /*
     * 排序
     * date: 2019-04-10
     * author: admin
     */
    public function sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['sort'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['sort'] < 0 || $post['sort'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        Db::startTrans();
        try {

            $res = Db::name('pic_banner')->where(array('id'=>$post['id']))->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('pic_banner')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['sort'])
                ->order('sort', 'asc')
                ->select();

            if (!Db::name('pic_banner')->where('id', '=', $post['id'])->update(['sort' => $post['sort']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['sort']+1;
            foreach ($rows as &$v) {
                if ($v['sort'] != $i) {
                    if (!Db::name('pic_banner')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }




    //快捷
    public function quick()
    {
        return View::fetch();
    }

//快捷
    public function quick_load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $total = Db::name('pic_home_set')
            ->count();
        $rows = Db::name('pic_home_set')
            ->order(['store' => 'asc', 'id' => 'desc'])
            ->select();
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    /*
   * 修改
   */
    public function quick_edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->param('id');
        $inf = Db::name('pic_home_set')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }


    public function quick_modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);
//
//        // 验证
//        try {
//
//            validate(CheckQuick::class)->check($post);
//
//        } catch (ValidateException $e) {
//
//            return $this->outputAjax($e->getError());
//        }
        $update = array(
            'id'          => $post['id'],
            'title'       => !empty($post['title'])?$post['title']:'',
            'des'       => !empty($post['des'])?$post['des']:'',
//            'icon'       => $post['icon'],
            'type'       => $post['type'],
            'images'         => $post['images'],
            'url'         => $post['url'],
            'update_time' => time(),
        );
        if (!Db::name('pic_home_set')->strict(false)->update($update)) {
            return $this->outputAjax('操作失败！');
        }
        return $this->outputAjax('操作成功！',0);

    }

    /*
 * 排序
 * date: 2019-04-10
 * author: admin
 */
    public function quick_sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['store'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['store'] < 0 || $post['store'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        Db::startTrans();
        try {

            $res = Db::name('pic_home_set')->where(array('id'=>$post['id']))->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('pic_home_set')
                ->where('id', '<>', $post['id'])
                ->where('store', '>=', $post['store'])
                ->order('store asc')
                ->select();

            if (!Db::name('pic_home_set')->where('id', '=', $post['id'])->update(['store' => $post['store']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['store']+1;
            foreach ($rows as &$v) {
                if ($v['store'] != $i) {
                    if (!Db::name('pic_home_set')->where('id', '=', $v['id'])->update(['store' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }



    //热门关键词
    public function remen(){
        return View::fetch();
    }

    //列表
    public function renmen_load(Request $request){
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        $get =$request->get();
        $total = Db::name('pic_search')
            ->count();
        $rows = Db::name('pic_search')
            ->order(['sort' => 'desc','num'=>'desc', 'addtime' => 'desc'])
            ->page($get['page'], $get['limit'])
            ->select();
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    //修改
    public function remen_edit(Request $request){
        if ($request->isPost()){
            if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
                return $this->outputAjax('无操作权限');
            }
            $post = $request->post();
            $ret = Db::name('pic_search')
                ->where('id',$post['id'])
                ->update(['title'=>$post['title'],'addtime'=>date('Y-m-d H:i:s')]);
            if ($ret){
                return $this->outputAjax('操作成功！',0);
            }
            return $this->outputAjax('操作失败！');
        }
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }
        $id = $request->param('id');
        $inf = Db::name('pic_search')->find($id);
        View::assign('inf',$inf);
        return View::fetch();
    }

    public function remen_sort(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post)) {
            return $this->outputAjax('参数缺失！');
        }

        if (!is_numeric($post['store'])) {
            return $this->outputAjax('请填写数字！');
        }

        if ($post['store'] < 0 || $post['store'] > 999) {
            return $this->outputAjax('排序数字在0-999之间！');
        }

        Db::startTrans();
        try {

            $res = Db::name('pic_search')->where(array('id'=>$post['id']))->find();
            if (!$res) {
                return $this->outputAjax('参数错误！');
            }


            $rows = Db::name('pic_search')
                ->where('id', '<>', $post['id'])
                ->where('sort', '>=', $post['store'])
                ->order('sort asc')
                ->select();

            if (!Db::name('pic_search')->where('id', '=', $post['id'])->update(['sort' => $post['store']])) {
                Db::rollback();
                return $this->outputAjax('排序失败[1]！');
            }

            $i = $post['store']+1;
            foreach ($rows as &$v) {
                if ($v['store'] != $i) {
                    if (!Db::name('pic_search')->where('id', '=', $v['id'])->update(['sort' => $i])) {
                        Db::rollback();
                        return $this->outputAjax('排序失败[2]！');
                    }
                }
                $i++;
            }

            Db::commit();
            return $this->outputAjax('排序成功！', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }




}